import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'

import { Table, Button, Badge, message, Popconfirm, Icon, Alert, Col, Row } from 'antd';

import codingRuleService from 'containers/setting/coding-rule/coding-rule.service'
import menuRoute from 'routes/menuRoute'
import BasicInfo from 'components/basic-info'
import NewCodingRuleValue from 'containers/setting/coding-rule/new-coding-rule-value'
import SlideFrame from "components/slide-frame";
import ResizeTable from "components/resize-table";

class CodingRuleValue extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      editing: false,
      loading: true,
      data: [],
      page: 0,
      pageSize: 10,
      columns: [
        {title: messages('setting.key227'/*顺序号*/), dataIndex: "sequence", width: '15%'},
        {title: messages('setting.key228'/*参数名称*/), dataIndex: "segmentName", width: '15%'},
        {title: messages('setting.key229'/*参数值*/), dataIndex: "value", width: '50%'},
        {title: messages('setting.key225'/*状态*/), dataIndex: 'isEnabled', width: '10%', render: isEnabled => (
          <Badge status={isEnabled ? 'success' : 'error'} text={isEnabled ? messages('common.status.enable') : messages('common.status.disable')} />)},
        {title: messages('common.operation'), key: 'operation', width: '10%', render: (text, record) => (
          <span>
            <Popconfirm onConfirm={(e) => this.deleteItem(e, record)} title={messages('common.confirm.delete')/*确定要删除吗*/}>
              <a href="#" onClick={(e) => {e.preventDefault();e.stopPropagation();}}>{messages('common.delete')}</a>
            </Popconfirm>
          </span>)},  //操作
      ],
      pagination: {
        total: 0
      },
      updateState: false,
      infoList: [
        {type: 'input', label: messages('setting.key230'/*编码规则代码*/), id: 'codingRuleCode', disabled: true},
        {type: 'input', label: messages('setting.key231'/*编码规则名称*/), id: 'codingRuleName'},
        {type: 'value_list', label: messages('setting.key232'/*重置频率*/), id: 'resetFrequence', options: [], valueListCode: 2024},
        {type: 'input', label: messages('setting.key233'/*备注*/), id: 'remark'},
        {type: 'switch', label: messages('setting.key225'/*状态*/), id: 'isEnabled'}
      ],
      infoData: {},
      showSlideFrameFlag: false,
      nowCodingRuleValue: null,
      codingRule: menuRoute.getRouteItem('coding-rule'),
      nowSequence: 1
    };
  }

  deleteItem = (e, record) => {
    this.setState({loading: true});
    codingRuleService.deleteCodingRuleObject(record.id).then(res => {
      this.getList();
      message.success(messages('common.delete.success', {name: ''}));  //删除成功
    }).catch(e => {
      this.setState({ loading: false });
      message.error(`${e.response.data.message}`)
    })
  };

  componentWillMount(){
    this.getList();
    codingRuleService.getCodingRule(this.props.params.ruleId).then(res => {
      res.data.resetFrequence = {label: res.data.resetFrequenceName, value: res.data.resetFrequence};
      this.setState({ infoData: res.data })
    })
  }

  //得到列表数据
  getList(){
    this.setState({ loading: true });
    return codingRuleService.getCodingRuleValueList(this.state.page, this.state.pageSize, this.props.params.ruleId).then((response)=>{
      response.data.map((item)=>{
        item.key = item.id;
        switch(item.segmentType){
          case '10':
            item.value = item.segmentValue;
            break;
          case '20':
            item.value = item.dateFormat;
            break;
          case '50':
            item.value = `${messages('setting.key234'/*位数*/)}：${item.length}、  ${messages('setting.key235'/*步长*/)}：${item.incremental}、  ${messages('setting.key236'/*开始值*/)}：${item.startValue}`;
            break;
          default:
            item.value = '-';
        }
      });
      let nowSequence = 1;
      if(response.data.length > 0)
        nowSequence = response.data[response.data.length - 1].sequence + 1;
      this.setState({
        nowSequence,
        data: response.data,
        loading: false,
        pagination: {
          total: Number(response.headers['x-total-count']),
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    });
  }

  //分页点击
  onChangePager = (page) => {
    if(page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, ()=>{
        this.getList();
      })
  };

  updateInfo = (params) => {
    this.setState({editing: true});
    codingRuleService.updateCodingRule(Object.assign({}, this.state.infoData, params)).then(res => {
      codingRuleService.getCodingRule(this.props.params.ruleId).then(res => {
        res.data.resetFrequence = {label: res.data.resetFrequenceName, value: res.data.resetFrequence};
        this.setState({updateState: true, editing: false, infoData: res.data});
        message.success(messages('common.save.success', {name: ''}));  //保存成功
      });
    }).catch((e)=> {
      if (e.response) {
        message.error(`${messages('common.save.filed')/*保存失败*/}, ${e.response.data.message}`);
        this.setState({editing: false});
      }
    })
  };

  handleNew = () => {
    this.setState({
      nowCodingRuleValue: null,
      showSlideFrameFlag: true
    })
  };

  handleRowClick = (record) => {
    this.setState({
      nowCodingRuleValue: record,
      showSlideFrameFlag: true
    })
  };

  afterClose = (params) => {
    params && this.getList();
    this.setState({ showSlideFrameFlag: false, nowCodingRuleValue: null });
  };

  render(){
    const { columns, data, loading,  pagination, infoList, infoData, updateState, showSlideFrameFlag, nowCodingRuleValue, editing, nowSequence } = this.state;

    return (
      <div>
        <BasicInfo infoList={infoList}
                   infoData={infoData}
                   updateState={updateState}
                   updateHandle={this.updateInfo}
                   loading={editing}/>
        <div className="table-header">
          <div className="table-header-title">{messages('common.total', {total: pagination.total ? pagination.total : '0'})}</div> {/* 共total条数据 */}
          <div className="table-header-buttons">
            <Row gutter={20}>
              <Col span={4}><Button type="primary" style={{ height: 39 }} onClick={this.handleNew}>{messages('setting.key237'/*新建规则明细*/)}</Button></Col>
              <Col span={20}><Alert message={messages('setting.key238'/*段值必须维护序列号，否则编码无法生成。不同规则的日期格式尽量相同。*/)} type="info" showIcon /></Col>
            </Row>
          </div>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          onRow={record => ({onClick: () => this.handleRowClick(record)})}
          rowKey="id"
          bordered
          size="middle"
        />

        <a className="back" onClick={() => {this.context.router.push(this.state.codingRule.url.replace(":id", this.props.params.id));}}>
          <Icon type="rollback" style={{marginRight:'5px'}}/>{messages('common.back')/*返回*/}
        </a>

        <SlideFrame content={NewCodingRuleValue}
                    show={showSlideFrameFlag}
                    params={{ codingRuleId: this.props.params.ruleId, nowCodingRuleValue, nowSequence }}
                    onClose={() => {this.setState({ showSlideFrameFlag: false })}}
                    afterClose={this.afterClose}
                    title={messages('setting.key239'/*添加段值*/)}/>

      </div>
    )
  }

}

CodingRuleValue.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps() {
  return {}
}

export default connect(mapStateToProps)(CodingRuleValue);
